package com.jqb.jspcart.service.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;

import com.jqb.jspcart.bean.Hardware;
import com.jqb.jspcart.util.DBHandler;

public class OrderServiceImpl {
	
	public boolean createOrder(CartServiceImpl cart , String username) {
		boolean flag = false;
		Connection conn = DBHandler.newInstance().getConnection();
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		try {
			conn.setAutoCommit(false);
			//修改数据隔离级别(一般很少去修改各个数据库的默认隔离级别)
			//conn.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
			String sql = "insert into orders(payment,status,username) values(?,?,?) ";
			pstmt = conn.prepareStatement(sql);
			pstmt.setFloat(1, cart.getSum());
			pstmt.setInt(2, 0);
			pstmt.setString(3, username);
			pstmt.executeUpdate();
			sql="select sq_ordersid.currval from orders";
			pstmt = conn.prepareStatement(sql);
			rs = pstmt.executeQuery();
			int oid  = 0;
			if (rs.next()) {
				oid = rs.getInt(1);
			}
			System.out.println("oid="+oid);
			ArrayList<Hardware> goodsList = cart.getGoods();
			Iterator<Hardware> it = goodsList.iterator();
			while(it.hasNext()){
				Hardware goods = it.next();
				sql="insert into orderdetail(oid,gid,name,num) values(?,?,?,?)";
				pstmt = conn.prepareStatement(sql);
				pstmt.setInt(1, oid);
				pstmt.setInt(2, goods.getId());
				pstmt.setString(3, goods.getName());
				pstmt.setInt(4, goods.getNum());
				pstmt.executeUpdate();
			}
			conn.commit();
			flag = true;
		} catch (SQLException e) {
			flag = false;
			try {
				conn.rollback();
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
			e.printStackTrace();
		}finally{
			DBHandler.close(conn, pstmt, rs);
		}
		return flag;
	}
	
	public static OrderServiceImpl newInstance(){
		return new OrderServiceImpl();
	}
}

